import request from '../../common/request';
import {wlq_order} from '../../common/config'
Page({
  data:{
    IsActive:0,
    orderList:[],
    // 页数
    page:1,
    // 状态
    state:0,
    // 没有数据加载
    isEnd:false
  },

  // 发送请求的函数
  async getOrderList(page=1,state=0){
    let {orderList} =  this.data;

    const token = wx.getStorageSync('cookie');
    const URL = `${wlq_order}/order/list/${page}?access_token=${token}&type=0&state=${state}`;
    const res = await request(URL);

    const temp = [...orderList,...res.data]
    if(res.code===200){
      console.log('数组的长度',res.data.length)
      if(res.data.length == 0){
        this.setData({
          isEnd:true
        })
      }
      this.setData({
        orderList:temp
      })
    }
  },

  // 获取可取消
  handleOrder(){
    let {page,state} = this.data;
    page = 1;
    state = 0;
    this.setData({
      IsActive:0,
      page,
      orderList:[],
      isEnd:false,
      state:''
    })
    this.getOrderList(page,state);

  },

  // 待收货
  handleGoods(){
    let {page,state} = this.data;
    page = 1;
    state = 1;

    // 卖家已经接受订单
    this.setData({
      IsActive:1,
      state,
      page,
      orderList:[],
      isEnd:false

    })
    this.getOrderList(page,state);

  },

  // 已取消
  handleCancel(){
    console.log('已取消列表')
    let {page,state} = this.data;
    page = 1;
    state = 2;

    this.setData({
      IsActive:2,
      state,
      page,
      orderList:[],
      isEnd:false

    })
    this.getOrderList(page,state);

  },

  // 已完成
  handleFinish(){
    let {page,state} = this.data;
    page = 1;
    state = 4;
    this.setData({
      IsActive:3,
      state,
      page,
      orderList:[],
      isEnd:false
    })
    this.getOrderList(page,state);
  },

  onLoad(){
    // 初次加载数据
    this.getOrderList();
  },

  // 点击取消订单
  async cancelOrder(e){
    console.log(e.currentTarget.dataset.id);
    const  orderId = e.currentTarget.dataset.id;
    let {orderList} =  this.data;
    const token =wx.getStorageSync('cookie');
    const URL = `${wlq_order}/order?access_token=${token}`;
    const res = await request(URL,'PUT',JSON.stringify({
      orderId,
      state:2
    }));
    console.log('取消订单',res)
    if(res.code === 200){
      const index = orderList.findIndex(item=>item.orderId===orderId);
      orderList.splice(index,1);
      this.setData({
        orderList
      })
    }
  },

  // 触底加载更多数据
  getMoreOrder(){
    // isEnd为true表示没有更多数据可以加载了
    if(this.data.isEnd){
      return;
    }
    let {page,state} = this.data;
    page++;

    console.log('触底加载更多数据',page,state);
    this.getOrderList(page,state);
    this.setData({
      page
    })
  },

  // 跳转到商品详情页
  navToGoodsDetail(e){
    wx.navigateTo({
      url: `/pages/goods_detail/goods_detail?goodsId=${e.currentTarget.dataset.id}`,
    });
  }

})